package com.example.logisticsingle.filter;


import com.example.logisticsingle.constants.Config;
import com.example.logisticsingle.entity.SSOUser;
import com.example.logisticsingle.login.SSOTokenLoginHelper;
import com.example.logisticsingle.path.AntPathMatcher;

import lombok.extern.slf4j.Slf4j;


import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * sso filter for APP
 *
 */

@Slf4j
public class SSOTokenFilter extends HttpServlet implements Filter {
    /**
     *
     */
    private static final long serialVersionUID = 2807887262012957656L;

    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private String ssoServer;
    private String logoutPath;
    private String excludedPaths;

    public void init(FilterConfig filterConfig) throws ServletException {
        ssoServer = filterConfig.getInitParameter(Config.SSO_SERVER);
        logoutPath = filterConfig.getInitParameter(Config.SSO_LOGOUT_PATH);
        excludedPaths = filterConfig.getInitParameter(Config.SSO_EXCLUDED_PATHS);
        log.info("SsoTokenFilter init.");
    }



    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String servletPath = req.getServletPath();
        /**
         *  无须要授权操作URL
         */
        if( (excludedPaths!=null && excludedPaths.trim().length()>0) ){
            for (String excludedPath:excludedPaths.split(",")) {
                String uriPattern = excludedPath.trim();

                // 支持ANT表达式
                if (antPathMatcher.match(uriPattern, servletPath)) {
                    // excluded path, allow
                    chain.doFilter(request, response);
                    return;
                }

            }
        }

        // logout filter
        if (logoutPath!=null
                && logoutPath.trim().length()>0
                && logoutPath.equals(servletPath)) {

            chain.doFilter(request, response);
            return;
        }
        //login check
        SSOUser user = SSOTokenLoginHelper.loginCheck(req);
        if (user == null) {
            // response
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":"+501+", \"msg\":\""+ "sso not login." +"\"}");
            return;
        }

        // ser sso user
        request.setAttribute(Config.SSO_USER, user);

        /**
         * 已登录，放行
         */
        chain.doFilter(request, response);
        return;
    }

}
